/**
 * 
 */
package com.monkeyboy.security.social.qq.api;

import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @Description
 *
 * @author Gavin<br>
 *         2019年8月27日
 */
public class QQimpl extends AbstractOAuth2ApiBinding implements QQ {
	private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";// 获取openid的地址
	private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";// 获取用户信息的地址
	private String appId;
	private String openId;
	private ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
			false);// ignore unknown properties in the JSON:

	public QQimpl(String accessToken, String appId) {// 该构造方法主要是为了获取openid
		// 这儿调用super的构造方法是因为父类提供了accessToken的处理，我们每次请求都会自动在链接后面加上accessToken
		super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
		this.appId = appId;
		String url = String.format(URL_GET_OPENID, accessToken);
		String result = getRestTemplate().getForObject(url, String.class);
		System.err.println(result);
		this.openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");// 从返回的字符串获取openid
		// 此时，三个参数都有了
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.monkeyboy.security.social.qq.api.QQ#getUserInfo()
	 */
	@Override
	public QQUserInfo getUserInfo() {
		String url = String.format(URL_GET_USERINFO, appId, openId);// 这儿不用加accessToken，因为父类会自动给我们加上
		String result = getRestTemplate().getForObject(url, String.class);// 获取到的QQ用户信息
		System.err.println("result userInfo：" + result);
		QQUserInfo userInfo = null;
		try {
			userInfo = objectMapper.readValue(result, QQUserInfo.class);
			userInfo.setOpenId(openId);
			return userInfo;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("QQ获取用户信息失败", e);
		}
	}

}
